package com.slfx.open.api.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/* 
 * 
'============================================================================ 
'api说明： 
'createSHA1Sign创建签名SHA1 
'getSha1()Sha1签名 
'============================================================================ 
'*/
@Slf4j
public class SHA1Util {
    //微信公众号开发的获取时间戳
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    //创建签名SHA1
    public static String createSHA1Sign(SortedMap<String, String> signParams) {
        StringBuffer sb = new StringBuffer();
        Set<Entry<String, String>> es = signParams.entrySet();
        Iterator<Entry<String, String>> it = es.iterator();
        while (it.hasNext()) {
            Entry<String, String> entry = (Entry<String, String>) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            sb.append(k + "=" + v + "&");
            //要采用URLENCODER的原始值！  
        }
        String params = sb.substring(0, sb.lastIndexOf("&"));
        log.info(params);
        return getSha1(params);
    }

    //Sha1签名  
    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            log.error("getSha1 error", e);
            throw new RuntimeException(e.getMessage(), e);
        }
    }


    /**
     * 规范化转换
     *
     * @param sortedParamMap
     * @return
     */
    public static String canonicalize(SortedMap<String, String> sortedParamMap) {
        if (sortedParamMap.isEmpty()) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        Iterator<Entry<String, String>> iter = sortedParamMap.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<String, String> kvpair = iter.next();
            buffer.append(percentEncodeRfc3986(kvpair.getKey()));
            buffer.append("=");
            buffer.append(kvpair.getValue());
            if (iter.hasNext()) {
                buffer.append("&");
            }
        }
        String canonical = buffer.toString();
        return canonical;
    }

    /**
     * Rfc3986</br>
     * 此处建议使用spring的encodeUri方法
     * http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/
     * web/util/UriUtils.html
     *
     * @param s
     * @return
     */
    private static String percentEncodeRfc3986(String s) {
        String out;
        try {
            out = URLEncoder.encode(s, "utf-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (UnsupportedEncodingException e) {
            out = s;
        }
        return out;
    }

    public static void main(String[] args) {
//    	String str = "appId=8b8e9dce-0ade-4a38-8cb4-8acbc3726591";
//    	String aa = str + "35390e1809b948cba5c2d6d73218e75f";
//    	System.out.println(getSha1(aa));
        SortedMap<String, String> map = new TreeMap<String, String>();
//    	String currentTimeStr = System.currentTimeMillis() + "";
//    	System.out.println(currentTimeStr);
//    	map.put("opfid", "8b8e9dce-0ade-4a38-8cb4-8acbc3726591");
//    	map.put("nonce", "fsdhfa");
//    	map.put("timestamp", currentTimeStr);
//    	map.put("secret", "35390e1809b948cba5c2d6d73218e75f");
//    	System.out.println(createSHA1Sign(map));

        //nonce=rabbit&timestamp=1531207831833&uid=356546565756756&opfid=95668370284249012219&appid=fa478580-e5d8-485d-ac75-f55b9a68c8c8&enterpriseid=be_A2FfURmb5&signature=2284cf811e990315a16b50d5384142bb07c48725

        map.put("opfid", "95668370284249012219");
        map.put("enterpriseid", "55306108c51369f023cf59b2");
        map.put("appid", "fa478580-e5d8-485d-ac75-f55b9a68c8c8");
        map.put("uid", "356546565756756");
        map.put("nonce", "rabbit");
        map.put("timestamp", "1531207831833");
        map.put("secret", "asdfsdafsdafsdafsd");
//    	map.put("groupby", "dt");
//    	map.put("page", "1");
//    	map.put("pageSize", "10");
        //b1d6fce5dbc0f73f719fa304d51ddafb464ce20e
        System.out.println(createSHA1Sign(map));
    }
}  
